<template>
  <view class="booking-details-page">
    <!-- 核销码 -->
    <view class="verification-section">
      <view class="verification-code">核销码: {{verificationCode}}</view>
      <view class="qr-code">
        <uqrcode 
          ref="uqrcode" 
          canvas-id="qrcode-canvas" 
          :value="qrCodeData" 
          :options="qrCodeOptions"
          @complete="onQRCodeComplete"
          v-if="qrCodeData"
          @click="previewQRCode"
        ></uqrcode>
        <view v-if="!qrCodeData" class="qr-loading">
          <text>生成二维码中...</text>
        </view>
      </view>
    </view>
    
    <!-- 维修信息 -->
    <view class="info-section">
      <view class="section-title">维修信息</view>
      <view class="info-list">
        <view class="info-item">
          <text class="info-label">维修单号</text>
          <text class="info-value">{{bookingData.maintenanceOrderNumber}}</text>
        </view>
        <view class="info-item">
          <text class="info-label">维修状态</text>
          <text class="info-value status-in-progress">{{bookingData.status}}</text>
        </view>
        <view class="info-item">
          <text class="info-label">车主姓名</text>
          <text class="info-value">{{bookingData.customerInfo.name}}</text>
        </view>
        <view class="info-item">
          <text class="info-label">联系方式</text>
          <text class="info-value">{{bookingData.customerInfo.phone}}</text>
        </view>
        <view class="info-item">
          <text class="info-label">维修方式</text>
          <text class="info-value">{{getRepairMethodText(bookingData.repairMethod)}}</text>
        </view>
        <view class="info-item" v-if="bookingData.repairMethod === 'pickup'">
          <text class="info-label">取车位置</text>
          <text class="info-value">{{bookingData.customerInfo.pickupLocation}}</text>
        </view>
        <view class="info-item">
          <text class="info-label">预约日期</text>
          <text class="info-value">{{formatAppointmentDate(bookingData.customerInfo.appointmentDate)}}</text>
        </view>
        <view class="info-item">
          <text class="info-label">提交日期</text>
          <text class="info-value">{{formatSubmissionDate(bookingData.createTime)}}</text>
        </view>
      </view>
    </view>
    
    <!-- 车辆信息 -->
    <view class="info-section">
      <view class="section-title">车辆信息</view>
      <view class="info-list">
        <view class="info-item">
          <text class="info-label">车辆类型</text>
          <text class="info-value">{{bookingData.vehicleInfo.type}}</text>
        </view>
        <view class="info-item">
          <text class="info-label">车牌号</text>
          <text class="info-value">{{bookingData.vehicleInfo.plateNumber}}</text>
        </view>
      </view>
    </view>
    
    <!-- 整车照片 -->
    <view class="photo-section">
      <view class="section-title">整车照片</view>
      <view class="photo-container">
        <image 
          v-if="bookingData.photos.full" 
          :src="bookingData.photos.full" 
          mode="aspectFill" 
          class="photo-image"
          @click="previewImage(bookingData.photos.full)"
        ></image>
        <view v-else class="photo-placeholder">
          <text class="placeholder-text">暂无照片</text>
        </view>
      </view>
    </view>
    
    <!-- 维修部位照片 -->
    <view class="photo-section">
      <view class="section-title">维修部位照片</view>
      <view class="photo-container">
        <image 
          v-if="bookingData.photos.repair" 
          :src="bookingData.photos.repair" 
          mode="aspectFill" 
          class="photo-image"
          @click="previewImage(bookingData.photos.repair)"
        ></image>
        <image 
          v-if="bookingData.photos.repair" 
          :src="bookingData.photos.repair" 
          mode="aspectFill" 
          class="photo-image"
          @click="previewImage(bookingData.photos.repair)"
        ></image>
        <image 
          v-if="bookingData.photos.repair" 
          :src="bookingData.photos.repair" 
          mode="aspectFill" 
          class="photo-image"
          @click="previewImage(bookingData.photos.repair)"
        ></image>
        <view v-if="!bookingData.photos.repair" class="photo-placeholder">
          <text class="placeholder-text">暂无照片</text>
        </view>
      </view>
    </view>
    
    <!-- 取消订单按钮 -->
    <view class="cancel-section">
      <button class="cancel-btn" @click="cancelOrder">取消订单</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      bookingNumber: '',
      verificationCode: '',
      qrCodeData: '',
      qrCodeOptions: {
        margin: 10,
        width: 200,
        height: 200,
        colorDark: '#000000',
        colorLight: '#FFFFFF',
        correctLevel: 'H',
        background: '#FFFFFF',
        foreground: '#000000',
        padding: 0,
        quietZone: 10
      },
      bookingData: {
        maintenanceOrderNumber: '',
        status: '进行中',
        customerInfo: {
          name: '张三',
          phone: '1993829282',
          appointmentDate: '2022-11-10',
          pickupLocation: '山阳区32号'
        },
        repairMethod: 'pickup',
        vehicleInfo: {
          type: '大客车',
          plateNumber: '豫J45323'
        },
        photos: {
          full: '/static/c1.png',
          repair: '/static/c2.png'
        },
        createTime: '2022-11-08 12:34'
      }
    }
  },
  
  onLoad(options) {
    // 设置页面标题
    uni.setNavigationBarTitle({
      title: '预约详情'
    });
    
    // 接收传递的预约数据
    if (options.bookingData) {
      try {
        const bookingData = JSON.parse(decodeURIComponent(options.bookingData));
        console.log('接收到的预约数据:', bookingData);
        this.bookingData = { ...this.bookingData, ...bookingData };
        console.log('合并后的预约数据:', this.bookingData);
      } catch (e) {
        console.error('解析预约数据失败：', e);
      }
    }
				
    // 接收预约编号
    if (options.bookingNumber) {
      this.bookingNumber = options.bookingNumber;
    }
    
    // 生成核销码和维修单号
    this.generateVerificationCode();
    this.generateMaintenanceOrderNumber();
    
    // 调试信息
    console.log('页面加载完成，当前数据:', this.bookingData);
    console.log('核销码:', this.verificationCode);
    console.log('维修单号:', this.bookingData.maintenanceOrderNumber);
    
    // 生成二维码数据
    this.generateQRCodeData();
  },
  
  methods: {
    // 生成核销码
    generateVerificationCode() {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
      let result = '';
      for (let i = 0; i < 8; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      this.verificationCode = result;
    },
    
    // 生成维修单号
    generateMaintenanceOrderNumber() {
      const timestamp = Date.now();
      const random = Math.floor(Math.random() * 1000000);
      this.bookingData.maintenanceOrderNumber = `${timestamp}${random}`.slice(-7);
    },
    
    // 生成二维码数据
    generateQRCodeData() {
      const qrData = {
        verificationCode: this.verificationCode,
        maintenanceOrderNumber: this.bookingData.maintenanceOrderNumber,
        customerInfo: this.bookingData.customerInfo,
        vehicleInfo: this.bookingData.vehicleInfo,
        repairMethod: this.bookingData.repairMethod,
        createTime: this.bookingData.createTime,
        timestamp: Date.now()
      };
      
      this.qrCodeData = JSON.stringify(qrData);
      console.log('二维码数据:', this.qrCodeData);
    },
    
    // 二维码生成完成回调
    onQRCodeComplete(e) {
      console.log('二维码生成完成:', e);
      if (e.success) {
        console.log('二维码生成成功');
      } else {
        console.error('二维码生成失败:', e.errMsg);
      }
    },
    
    // 预览二维码
    previewQRCode() {
      if (this.$refs.uqrcode) {
        this.$refs.uqrcode.toTempFilePath({
          success: (res) => {
            uni.previewImage({
              urls: [res.tempFilePath],
              current: res.tempFilePath
            });
          },
          fail: (err) => {
            console.error('预览二维码失败:', err);
          }
        });
      }
    },
    
    // 获取维修方式文本
    getRepairMethodText(method) {
      return method === 'store' ? '到店维修' : '上门取车';
    },
    
    // 格式化预约日期
    formatAppointmentDate(dateString) {
      if (!dateString) return '';
      
      // 处理不同的日期格式
      let date;
      if (typeof dateString === 'string') {
        // 如果是 YYYY-MM-DD 格式，添加时间
        if (dateString.includes('-') && !dateString.includes(':')) {
          date = new Date(dateString + ' 11:00');
        } else {
          date = new Date(dateString);
        }
      } else {
        date = new Date(dateString);
      }
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return dateString; // 如果解析失败，直接返回原字符串
      }
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}/${month}/${day} ${hours}:${minutes}`;
    },
    
    // 格式化提交日期
    formatSubmissionDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}/${month}/${day} ${hours}:${minutes}`;
    },
    
    // 预览图片
    previewImage(url) {
      if (!url) return;
      
      // 构建图片数组用于预览
      const imageUrls = [];
      if (this.bookingData.photos.full) {
        imageUrls.push(this.bookingData.photos.full);
      }
      if (this.bookingData.photos.repair) {
        // 添加多张相同的维修照片用于演示
        for (let i = 0; i < 3; i++) {
          imageUrls.push(this.bookingData.photos.repair);
        }
      }
      
      uni.previewImage({
        urls: imageUrls.length > 0 ? imageUrls : [url],
        current: url
      });
    },
    
    // 取消订单
    cancelOrder() {
      uni.showModal({
        title: '确认取消',
        content: '确定要取消这个预约订单吗？',
        success: (res) => {
          if (res.confirm) {
            // 执行取消订单逻辑
            console.log('取消订单:', this.bookingNumber);
            
            // 更新订单状态
            this.bookingData.status = '已取消';
            
            uni.showToast({
              title: '订单已取消',
              icon: 'success'
            });
            
            // 延迟返回上一页
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          }
        }
      });
    }
  }
}
</script>

<style scoped>
.booking-details-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

/* 通用section样式 */
.verification-section,
.info-section,
.photo-section {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.verification-section {
  padding: 30rpx;
  text-align: center;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

/* 核销码样式 */
.verification-code {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  text-align: center;
  margin-bottom: 25rpx;
  letter-spacing: 1rpx;
}

.qr-code {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 8rpx;
}





.qr-loading {
  width: 200rpx;
  height: 200rpx;
  background-color: #f8f8f8;
  border: 2rpx dashed #ddd;
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #999;
}

/* 信息列表样式 */
.info-list {
  display: flex;
  flex-direction: column;
  gap: 25rpx;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 28rpx;
  color: #666;
  flex-shrink: 0;
  width: 160rpx;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  text-align: right;
  flex: 1;
}

.status-in-progress {
  color: #007AFF;
  font-weight: bold;
}

/* 照片样式 */
.photo-container {
  display: flex;
  gap: 20rpx;
  overflow-x: auto;
  padding-bottom: 10rpx;
}

.photo-image {
  width: 200rpx;
  height: 150rpx;
  border-radius: 10rpx;
  flex-shrink: 0;
  border: 1rpx solid #eee;
}

.photo-placeholder {
  width: 200rpx;
  height: 150rpx;
  background-color: #f8f8f8;
  border: 2rpx dashed #ddd;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.placeholder-text {
  font-size: 24rpx;
  color: #999;
}

/* 取消订单按钮 */
.cancel-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
  z-index: 100;
}

.cancel-btn {
  width: 100%;
  height: 80rpx;
  background-color: transparent;
  color: #007AFF;
  border: 2rpx solid #007AFF;
  border-radius: 40rpx;
  font-size: 32rpx;
  font-weight: bold;
}
</style>
